package net.documentshare.mytag;

import java.util.Map;

import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.content.IContentPagerHandle;
import net.simpleframework.core.IApplicationModule;
import net.simpleframework.core.ado.IDataObjectQuery;
import net.simpleframework.util.HTMLBuilder;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.ui.pager.db.AbstractDbTablePagerHandle;

public class MyTagsManagerTableHandle extends AbstractDbTablePagerHandle {
	@Override
	public IApplicationModule getApplicationModule() {
		return MyTagUtils.applicationModule;
	}

	@Override
	public Map<String, Object> getFormParameters(final ComponentParameter compParameter) {
		final Map<String, Object> parameters = super.getFormParameters(compParameter);
		putParameter(compParameter, parameters, IContentPagerHandle._VTYPE);
		putParameter(compParameter, parameters, IMyTagApplicationModule._CATALOG_ID);
		putParameter(compParameter, parameters, "_tagsSearch");
		return parameters;
	}

	@Override
	public IDataObjectQuery<?> createDataObjectQuery(final ComponentParameter compParameter) {
		final StringBuilder sql = new StringBuilder();
		sql.append("vtype=? and catalogid=?");
		final String tag = compParameter.getRequestParameter("_tagsSearch");
		if (StringUtils.hasText(tag)) {
			sql.append(" and tagtext like '%").append(tag).append("%'");
		}
		sql.append(" order by ttype desc");
		return MyTagUtils.getTableEntityManager(MyTagBean.class).query(
				new ExpressionValue(sql.toString(), new Object[] { MyTagUtils.getVtype(compParameter),
						MyTagUtils.applicationModule.getCatalogId(compParameter) }), MyTagBean.class);
	}

	@Override
	protected Map<Object, Object> getTableRow(final ComponentParameter compParameter, final Object dataObject) {
		final Map<Object, Object> rows = super.getTableRow(compParameter, dataObject);
		final MyTagBean tag = (MyTagBean) dataObject;
		final StringBuilder sb = new StringBuilder();
		final StringBuilder params = new StringBuilder();
		params.append(IMyTagApplicationModule._TAG_ID).append("=").append(tag.getId()).append("&").append(IContentPagerHandle._VTYPE).append("=")
				.append(MyTagUtils.getVtype(compParameter));
		sb.append("<a onclick=\"$Actions['_tagDelete']('").append(params).append("');\">").append("#(Delete)").append("</a>");
		sb.append(HTMLBuilder.SEP);
		sb.append("<a onclick=\"$Actions['newsTagRWindow']('").append(params).append("');\">").append("#(tags_manager.3)").append("</a>");
		sb.append(HTMLBuilder.SEP);
		sb.append("<a onclick=\"$Actions['_tagOptionsWindow']('").append(params).append("');\">#(tags_manager.6)</a>");
		rows.put("action", sb);
		return rows;
	}
}
